import func from './func.js'

import QQMapWX from './qqmap-wx-jssdk.js'

//开发者密钥
let txMapKey = '2NQBZ-RMHLG-YTMQD-IIHNV-NBHE5-6YB2U' 

const tMap = new QQMapWX({
	key:txMapKey  
});

export const systemSetting = {
  // 腾讯地图Key
  txKey: txMapKey,
  // 跳转App公共地址
  mapUrlConfig: {
    baidu: 'baidumap://map/walknavi',
    gaode: {
      ios: 'iosamap://navi',
      android: 'androidamap://viewMap'
    },
    tengxun: 'qqmap://map/marker'
  }
}

function navToMapWx(addressInfo) {
  const { lat, lng, name, address } = addressInfo
  wx.ready(function () {
    wx.openLocation({
      type: "gcj02",
      latitude: Number(lat),
      longitude: Number(lng),
      name: name,
      scale: 18,
      address: address || ''
    });
  })
}

/**
 * 打开高德或百度地图
 * @param {*} latitude
 * @param {*} longitude
 * @param {*} name  导航目的地名称
 * @param {*} type 1 百度地图 2 高德地图 3.腾讯地图
 */
function navToMapAppH5(addressInfo, type) {
  const { lat, lng, name, address } = addressInfo
  const addressStr = address || ''
  let url
  const u = navigator.userAgent
  //判断ios
  const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  //判断Android
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
  if (!isIOS && !isAndroid) {
     uni.showToast({
		title:"此设备暂不支持"
	})
  }

  if (type === 0) {
    // 百度
    url = `${systemSetting.mapUrlConfig.baidu}?destination=${lat},${lng}&title=${name}&content=${addressStr}&output=html&coord_type=gcj02&src=test`
  } else if (type === 2) {
    url = `${systemSetting.mapUrlConfig.tengxun}?marker=coord:${lat},${lng};title:${name};addr:${addressStr}&referer=${systemSetting.txKey}`
  } else {
    // 高德
    let params = `?sourceApplication=mingyue&poiname=${name}&lat=${lat}&lon=${lng}&dev=0&t=2`
    const { android, ios } = systemSetting.mapUrlConfig.gaode
    url = (isAndroid ? android : ios) + params
  }
  
  uni.showToast({
  	title:`选择跳转类型:${url}`
  })
  
  if (url) {
    window.location.href = url
	
	setTimeout(()=>{
		navToMapLink(addressInfo, type)
	},3000)
  }
}

function navToMapLink(addressInfo, type) {
  const { lat, lng, name, address } = addressInfo
  const addressStr = address || ''
  let url
  const u = navigator.userAgent
  //判断ios
  const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  //判断Android
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
  if (!isIOS && !isAndroid) {
     uni.showToast({
		title:"此设备暂不支持"
	})
  }

  if (type === 0) {
    // 百度
    url = `http://api.map.baidu.com/marker?location=${lat},${lng}&title=${name}&content=${addressStr}&output=html&coord_type=gcj02&src=test`
  } else if (type === 2) { // 腾讯地图
    url = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${lat},${lng};title:${name};addr:${addressStr}&referer=${systemSetting.txKey}`
  } else {
    // 高德
    url = `https://uri.amap.com/marker?position=${lng},${lat}&name=${name}`
  }
  
  uni.showToast({
  	title:`选择跳转类型:${url}`
  })
  
  if (url) {
    window.location.href = url
  }
}
// 判断微信环境
function isWx(){
  var ua = navigator.userAgent.toLowerCase();
  if (/micromessenger/.test(ua)) {
	if(wx.miniProgram){
		return new Promise(resolve => {
		  wx.miniProgram.getEnv(function (res) {
		    if (res.miniprogram) {
		      // 小程序种
		      resolve("mini-wx");
		    } else {
		      // 微信环境种
		      resolve("emb-wx");
		    }
		  });
		});
	}else
	{
		return new Promise(resolve => {
		  resolve("wx-h5");
		});
	}
  } else {
    // 不在微信种
    return new Promise(resolve => {
      resolve("no-wx");
    });
  }
}

function navToMap(addressInfo,type) {
  isWx().then((res) => {
	  uni.showToast({
	  	title:res
	  })
	  
    if (res == 'mini-wx' || res == 'emb-wx') {
      navToMapWx(addressInfo)
    }else if(res == 'wx-h5') 
	{
		navToMapLink(addressInfo,type)
	}
	else {
      navToMapAppH5(addressInfo,type)
    }
  })
}

function reverseGeocoder(info) {
	tMap.reverseGeocoder(info)
}
	
function geocoder(address) {
	return new Promise((resolve, reject) => {
		//调用地址解析接口
		tMap.geocoder({
			//获取表单传入地址
			address: address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
			success: function(res) { //成功后的回调
				resolve(res.result)
			},
			fail: function(error) {
				console.error(error);
				reject(error)
			},
			complete: function(res) {
				console.log(res);
			}
		})
	})
}
	
async function currentPos() {
	console.log('WHAT?')
	return new Promise((resolve, reject) => {
		console.log('PPPXX!')
		uni.getLocation({
			type: 'wgs84',
			success: function(location) {
				console.log('当前位置的经度：' + location.longitude);
				console.log('当前位置的纬度：' + location.latitude);

				reverseGeocoder({
					location: {
						latitude: location.latitude,
						longitude: location.longitude
					},
					success: function(component) {
						console.log("解析地址成功", component);
						console.log("当前地址：", component.result.address);
						//let component = component.result.address_component;
						console.log('FFFFFFFFFFFFFFFFXXXXXXXXXXXXX')
						resolve({location,component})
					},
					fail: function(res) {
						uni.showToast({
							title: '定位失败',
							duration: 2000,
							icon: "none"
						})

						// that.form.latitude = '';
						// that.form.longitude = '';
						// that.form.pos_name = '';
						console.log(res);

						reject('定位失败')
					},
					complete: function(res) { //无论成功失败都会执行
						console.log(res)
					},
				})
			}
		});
	})
}

 async function choosePos() {
	// uni.getLocation({
	// 	type: 'wgs84',
	// 	success: function (res) {
	// 		console.log('当前位置的经度：' + res.longitude);
	// 		console.log('当前位置的纬度：' + res.latitude);
	// 	}
	// });
	
	return new Promise((resolve,reject)=>{
		let that = this
		uni.chooseLocation({
			success: function(location) {
				console.log(location)
				console.log('位置名称：' + location.name);
				console.log('详细地址：' + location.address);
				console.log('纬度：' + location.latitude);
				console.log('经度：' + location.longitude);
		
				reverseGeocoder({
					location: {
						latitude: location.latitude,
						longitude: location.longitude
					},
					success: function(component) {
						console.log("解析地址成功", component);
						console.log("当前地址：", component.result.address);
						resolve({location,component})
					},
					fail: function(res) {
						uni.showToast({
							title: '定位失败',
							duration: 2000,
							icon: "none"
						})

						reject(res)
						//console.log(res);
					},
					complete: function(res) { //无论成功失败都会执行
		
					},
				})
			}
		});
	})
}
	
function getDistanceWGS84( lat1, lng1, lat2, lng2){
			var PI = 3.1415926;
			var EarthRadius = 6378137;
			var Rad = PI / 180.0;
			var radlat1 = lat1 * Rad;
			var radlat2 = lat2 * Rad;
			var a = radlat1 - radlat2;
			var b = (lng1 - lng2)*Rad;
			var s = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(radlat1)*Math.cos(radlat2)*Math.pow(Math.sin(b/2),2)));
			s = s*EarthRadius;
			s = Math.round(s * 100) / 100;
			return s;
}
	
export default {
	reverseGeocoder,
	geocoder,
	currentPos,
	choosePos,
	getDistanceWGS84,
	navToMap
}